package com.lvhx.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "测试RocketMq")
@RestController
@RequestMapping("/rocketmq")
public class RocketMqController {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @ApiOperation("发送普通消息")
    @RequestMapping(value = {"/sendMessage"}, method = RequestMethod.GET)
    public void sendMessage() {
        // 发送普通消息
        rocketMQTemplate.convertAndSend("test-topic", "Hello, RocketMQ!");

        // 发送带Tag的消息
        rocketMQTemplate.convertAndSend("test-topic:tagA", "Message with Tag");

        // 发送带Key的消息（用于消息追踪）
        rocketMQTemplate.syncSend("test-topic", MessageBuilder
                .withPayload("Message with Key")
                .setHeader(RocketMQHeaders.KEYS, "msg-key-123")
                .build());
    }

    @ApiOperation("发送事务型消息")
    @RequestMapping(value = {"/sendTransactionalMessage"}, method = RequestMethod.GET)
    public void sendTransactionalMessage() {
        rocketMQTemplate.sendMessageInTransaction(
                "order-topic",
                MessageBuilder.withPayload("Transactional Message").build(),
                null  // 可选：传递参数给 executeLocalTransaction
        );
    }
}
